﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FloodFree.Common;
using FloodFree.Web.Areas.Api.ViewModels;
using FloodFree.Web.Mailers;

namespace FloodFree.Web.Areas.Api.Controllers
{
    public class SensorUpdateController : BaseController
    {

        [HttpGet]
        public JsonResult Index()
        {
            return Json(new { update = new SensorUpdateViewModel() }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult Create(SensorUpdateViewModel update)
        {
            try
            {
                SensorUpdate updateData = new SensorUpdate();
                updateData.Sensor = db.Sensors.Where(x => x.SensorUUID.Equals(update.SensorUUID)).First();
                updateData.Date = DateTime.Now;
                updateData.StatusType = update.StatusType;
                updateData.Status = update.Status;

                db.SensorUpdates.Add(updateData);
                db.SaveChanges();

                
                new Notifier().Notify(updateData.Sensor.SensorId, updateData.StatusType, updateData.Status);


                return Json(new { Update = update });
            }
            catch(Exception ex)
            {
                return Json(new { Error = ex.Message });
            }
        }
        
      
    }
}
